<template>
  <div class="table-container" :style="{ height: containerHeight }">
    <!-- 表格主体 -->
    <el-table
      ref="elTable"
      v-bind="$attrs"
      :data="tableData"
      :height="tableHeight"
      :row-key="rowKey"
      v-on="$listeners"
      @selection-change="handleSelectionChange"
    >
      <!-- 多选列 -->
      <el-table-column
        v-if="showSelection"
        type="selection"
        width="55"
        :reserve-selection="reserveSelection"
      />

      <!-- 序号列 -->
      <el-table-column
        v-if="showIndex"
        label="序号"
        type="index"
        :width="indexWidth"
        :index="indexMethod"
      />

      <!-- 动态列渲染 -->
      <template v-for="(column, index) in columns">
        <el-table-column
          v-if="!column.children"
          :key="index"
          v-bind="getColumnProps(column)"
        >
          <template v-slot="scope">
            <!-- 自定义插槽 -->
            <slot
              v-if="column.slot"
              :name="column.prop"
              :row="scope.row"
              :index="scope.$index"
            />
            <!-- 嵌套数据（支持xxx.yyy格式） -->
            <span v-else-if="column.prop.indexOf('.') > -1">
              {{ getNestedValue(scope.row, column.prop) }}
            </span>
            <!-- 普通数据 -->
            <span v-else>{{ scope.row[column.prop] }}</span>
          </template>
        </el-table-column>

        <!-- 多级表头（递归组件） -->
        <table-column
          v-else
          :key="column.prop"
          :column="column"
        />
      </template>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      v-if="showPagination"
      background
      class="pagination"
      :current-page="currentPage"
      :page-sizes="pageSizes"
      :page-size="pageSize"
      :layout="paginationLayout"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { scrollToElement } from '@/utils/scroll-to';
// 多级表头子组件
const TableColumn = {
  name: 'TableColumn',
  components: {},
  props: {
    column: {
      type: Object,
      default: () => ({})
    }
  },
  render() {
    return (
      <el-table-column {...{ props: this.getColumnProps(this.column) }}>
        {this.column.children.map(child => {
          return child.children ? (
            <table-column column={child} key={child.prop} />
          ) : (
            <el-table-column
              {...{ props: this.getColumnProps(child) }}
              key={child.prop}
            />
          );
        })}
      </el-table-column>
    );
  },
  methods: {
    getColumnProps(column) {
      return {
        prop: column.prop,
        label: column.label,
        width: column.width,
        align: column.align || 'center',
        sortable: column.sortable ? 'custom' : false
      };
    }
  }
};

export default {
  name: 'TableList',
  components: { TableColumn },
  props: {
    // 表格列配置
    columns: {
      type: Array,
      default: () => []
    },
    // 表格数据
    tableData: {
      type: Array,
      default: () => []
    },
    // 分页相关
    showPagination: {
      type: Boolean,
      default: true
    },
    total: {
      type: Number,
      default: 0
    },
    pageSize: {
      type: Number,
      default: 10
    },
    currentPage: {
      type: Number,
      default: 1
    },
    // 序号列
    showIndex: {
      type: Boolean,
      default: true
    },
    indexWidth: {
      type: Number,
      default: 80
    },
    // 多选列
    showSelection: {
      type: Boolean,
      default: false
    },
    reserveSelection: {
      type: Boolean,
      default: false
    },
    // 自适应高度
    autoHeight: {
      type: Boolean,
      default: true
    },
    // 行key（用于多选保留）
    rowKey: {
      type: String,
      default: 'id'
    }
  },
  data() {
    return {
      tableHeight: null,
      pageSizes: [10, 20, 50, 100],
      paginationLayout: 'total, sizes, prev, pager, next, jumper'
    };
  },
  computed: {
    containerHeight() {
      return this.autoHeight ? 'calc(100% - 62px)' : 'auto';
    }
  },
  mounted() {
    this.autoHeight && this.calculateHeight();
    window.addEventListener('resize', this.calculateHeight);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.calculateHeight);
  },
  methods: {
    // 序号计算方法
    indexMethod(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1;
    },

    // 获取嵌套值
    getNestedValue(row, path) {
      return path.split('.').reduce((obj, key) => obj?.[key], row);
    },

    // 处理分页
    handleSizeChange(size) {
      this.$emit('update:pageSize', size);
      this.$emit('pagination-change');
      scrollToElement(document.querySelector('.el-table__body-wrapper'), 0, 200);
    },

    handleCurrentChange(page) {
      this.$emit('update:currentPage', page);
      this.$emit('pagination-change');
      scrollToElement(document.querySelector('.el-table__body-wrapper'), 0, 200);
    },

    // 自适应高度计算
    calculateHeight() {
      if (!this.autoHeight) return;
      this.$nextTick(() => {
        const rect = this.$el.getBoundingClientRect();
        this.tableHeight = rect.height - (this.showPagination ? 50 : 0);
      });
    },

    // 多选处理
    handleSelectionChange(selection) {
      this.$emit('selection-change', selection);
    },

    // 获取列属性
    getColumnProps(column) {
      return {
        prop: column.prop,
        label: column.label,
        width: column.width,
        align: column.align || 'center',
        sortable: column.sortable ? 'custom' : false,
        formatter: column.formatter
      };
    },

    // 暴露原生方法
    clearSelection() {
      this.$refs.elTable.clearSelection();
    }
  }
};
</script>

  <style scoped lang="scss">
  .table-container {
    position: relative;
    height: 100%;

    ::v-deep .el-table {
      th {
        background-color: #f5f7fa;
        color: #606266;
        font-weight: 600;
      }

      .el-table__row--striped td {
        background-color: #fafafa;
      }

      .el-table__cell {
        padding: 8px 0;
      }
    }

    .pagination {
      padding: 15px 0;
      text-align: right;
    }
  }
  </style>
